import React, { Component, useRef } from 'react'
import { SearchOutlined } from '@ant-design/icons';
import { Form, Input, Space, Button, DatePicker, Tabs, Steps, InputNumber,Select } from 'antd'
import _ from 'lodash'
import TheButton from '@/components/TheButton'
import TheTable from '@/components/TheTable'
import ThePagination from '@/components/ThePagination'
import TheDialog from '@/components/TheDialog'
import { apiGetShopOrderInfoPage, apiGetShopOrderInfoList } from '@/request/orderManagement'
import { getDateTime3, getDateTime2 } from '@/utils/getDate'
import { exportSheetTable } from '@/utils/exportTable.js'
import StockOutModal from "./stockOutModal";
import Logistics from "./logistics";

const { RangePicker } = DatePicker
const { TabPane } = Tabs
const { Step } = Steps

const SearchHeader = ({ getValue,exportDataList }) => {
  const formRef = useRef()
  const onFinish = (values) => {
    if (values.time && values.time.length) {
      values.createTimeStart = getDateTime3(values.time[0]) + ' 00:00:00'
      values.createTimeEnd = getDateTime3(values.time[1]) + ' 23:59:59'
    }
    delete (values.time)
    _.forIn(values, (v, k) => {
      if (!v) {
        delete (values[k])
      }
    })
    getValue(values)
  }
  const onlineExportOrderDetail = () => {
    exportDataList({ option: formRef.current.getFieldValue() })
  }
  const reset = () => {
    formRef.current.setFieldsValue({
      orderCode: '',
      time: [],
      memberId:'',
      activityTypeCode:null,
      memberMobile:'',
    })
    getValue({})
  }
  return (
    <Form ref={formRef} onFinish={onFinish} layout="inline">
      <Form.Item name="orderCode">
        <Input placeholder='请输入订单号' suffix={<SearchOutlined />} />
      </Form.Item>
      <Form.Item name="memberId">
        <InputNumber placeholder='用户id' suffix={<SearchOutlined />} />
      </Form.Item>
      <Form.Item name="memberMobile">
        <Input placeholder='手机号' suffix={<SearchOutlined />} />
      </Form.Item>
      <Form.Item name="activityTypeCode" >
        <Select allowClear options={[
          {
            value: '0',
            label: '普通订单'
          },
          {
            value: '1',
            label: '砍价订单'
          },
          {
            value: '2',
            label: '拼团订单'
          },
          {
            value: '3',
            label: '奖品订单'
          }
        ]} placeholder={"请选择订单类型"} style={{width:"160px"}} />
      </Form.Item>
      <Form.Item name="time" label="下单时间">
        <RangePicker />
      </Form.Item>
      <Form.Item>
        <Space>
          <Button htmlType="submit" type="primary">搜索</Button>
          <Button onClick={reset}>重置</Button>
        </Space>
      </Form.Item>
      <TheButton
              haspermi={['mallorder:list:export']}
              type="default"
              size="middle"
              onClick={onlineExportOrderDetail}
            >
              导出全部
            </TheButton>
    </Form>
  );
};

export default class MallOrder extends Component {
  logisticsRef = React.createRef()
  stockOutModalRef = React.createRef()
  state = {
    columns: [
      {
        title: '订单编号',
        dataIndex: 'orderCode',
        key: 'orderCode'
      },
      {
        title: '买家昵称',
        dataIndex: 'buyMemberName',
        key: 'buyMemberName'
      },
      {
        title: '用户手机号',
        dataIndex: 'orderMemberPhone',
        key: 'orderMemberPhone'
      },
      {
        title: '支付方式',
        dataIndex: 'payWay',
        key: 'payWay',
        render: (text) => {
          let label = ""
          switch (text) {
            case "WeChat":
              label = "微信";
              break;
            case "Alipay":
              label = "支付宝";
              break;
            case "YsPay":
              label = "银行卡";
              break;
          }
          return label;
        }
      },
      {
        title: '收货人',
        dataIndex: 'memberName',
        key: 'memberName'
      },
      {
        title: '收货人联系方式',
        dataIndex: 'memberPhone',
        key: 'memberPhone'
      },
      {
        title: '收货地址',
        dataIndex: 'memberAddress',
        key: 'memberAddress'
      },
      {
        title: '订单类型',
        dataIndex: 'activityTypeCode',
        key: 'activityTypeCode',
        render: (text) => {
          let label = ""
          switch (parseInt(text)) {
            case 0:
              label = "普通订单";
              break;
            case 1:
              label = "砍价订单";
              break;
            case 2:
              label = "拼团订单";
              break;
            case 3:
              label = "奖品订单";
              break;
            default:
              break;
          }
          return label;
        }
      },
      {
        title: '订单金额（元）',
        dataIndex: 'orderTotalPrice',
        key: 'orderTotalPrice',
        render: (text) => {
          return <React.$Price price={text} />
        }
      },
      {
        title: '实付金额（元）',
        dataIndex: 'orderPayPrice',
        key: 'orderPayPrice',
        render: (text) => {
          return <React.$Price price={text} />
        }
      },
      {
        title: '订单时间',
        dataIndex: 'createTime',
        key: 'createTime'
      },
      {
        title: '订单状态',
        dataIndex: 'orderState',
        key: 'orderState',
        render: (text) => {
          let label = ""
          switch (parseInt(text)) {
            case 3:
              label = "待付款";
              break;
            case 4:
              label = "待发货";
              break;
            case 5:
              label = "待收货";
              break;
            case 6:
              label = "待分享";
              break;
            case 9:
              label = "交易成功";
              break;
            case 0:
              label = "交易关闭";
              break;
          }
          return label;
        }
      },
      // {
      //   title: '测试用-包裹类型',
      //   dataIndex: 'outLibraryCount',
      //   key: 'outLibraryCount',
      //   render: (text, record) => {
      //     return text > 1 ? '多' : '单'
      //   }
      // },
      // {
      //   title: '测试用-快递类型',
      //   dataIndex: 'deliveryCode',
      //   key: 'deliveryCode',
      //   render: (text, record) => {
      //     if (record.outLibraryCount > 1){
      //       return '混合'
      //     }
      //     return text ? "自配送" : "快递"
      //   }
      // },
      {
        title: '操作',
        fixed: 'right',
        render: (text, record) => {
          return <>
            <TheButton haspermi={['order:mallOrder:detail']} onClick={() => this.props.history.push(`/order/mallOrder/details/${record.shopOrderId}`)}>查看订单</TheButton>
            {parseInt(record.orderState) === 5 && <TheButton haspermi={['order:mallOrder:logistics']} onClick={() => this.onLogistics(record)}>查看物流</TheButton>}
          </>
        }
      }
    ],
    dataSource: [],
    tabData: [
      {
        key: "",
        tab: '全部'
      },
      {
        key: "3",
        tab: '待付款'
      },
      {
        key: "6",
        tab: '待分享'
      },
      {
        key: "4",
        tab: '待发货'
      },
      {
        key: "5",
        tab: '待收货'
      },
      {
        key: "9",
        tab: '交易成功'
      },
      {
        key: "0",
        tab: '交易关闭'
      },
    ],
    pageData: {
      pageNo: 1,
      pageSize: 10
    },
    pageData3: {
      pageNo: 1,
      pageSize: 10
    },
    pageData4: {
      pageNo: 1,
      pageSize: 10
    },
    pageData5: {
      pageNo: 1,
      pageSize: 10
    },
    pageData6: {
      pageNo: 1,
      pageSize: 10
    },
    pageData9: {
      pageNo: 1,
      pageSize: 10
    },
    pageData0: {
      pageNo: 1,
      pageSize: 10
    },
    total3: 0,
    total4: 0,
    total5: 0,
    total6: 0,
    total9: 0,
    total0: 0,
    searchValue: {},
    orderState: "",
    loading: false
  }
  componentDidMount() {
    this.getData()
  }
  getData = async () => {
    this.setState({ loading: true })
    const { searchValue, orderState } = this.state
    let res = await apiGetShopOrderInfoPage({ orderState, ...searchValue, ...this.state[`pageData${orderState}`] })
    if (res.code === 0 && res.data) {
      this.setState({
        dataSource: res.data,
        [`pageData${orderState}`]: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        [`total${orderState}`]: res.totalCount
      })
    }
    this.setState({ loading: false })
  }
  pageChange = (pageNo, pageSize) => {
    const { orderState } = this.state
    this.setState({
      [`pageData${orderState}`]: {
        pageNo,
        pageSize
      }
    }, () => {
      this.getData()
    })
  }
  getValue = value => {
    const { orderState } = this.state
    this.setState({
      [`pageData${orderState}`]: {
        pageNo: 1,
        pageSize: 10
      },
      searchValue: value
    }, () => {
      this.getData()
    })
  }
  changeKey = key => {
    this.setState({
      orderState: key
    }, () => {
      this.getData()
    })
  }
  onLogistics = async value => {
    // isMultiPackage是否为多包裹 true：多包裹 false: 单包裹
    let isMultiPackage = value.outLibraryCount > 1;
    if (isMultiPackage) {
      this.stockOutModalRef.current.open(value.shopOrderId)
    } else {
      if (value.deliveryCode) {
        this.props.history.push(`/order/mallOrder/details/${value.shopOrderId}/normal`)
      } else {
        this.logisticsRef.current.onLogistics(value.shopOrderId, value.oneOutLibraryCode)
      }
    }
  }

  exportAll = async (e) => {
    const { searchValue, orderState } = this.state
    let res = await apiGetShopOrderInfoList({ ...searchValue, orderState })
    if (res.code === 0 && res.data) {
      console.log(res.data);
      const th_arr = [
        {
          title: '商城订单列表',
          prop: '',
          children: [
            {
              title: '订单编号',
              prop: 'orderCode',
            },
            {
              title: '买家昵称',
              prop: 'buyMemberName',
            },
            {
              title: '用户手机号',
              prop: 'orderMemberPhone',
            },
            {
              title: '支付方式',
              prop: 'payWay',
            },
            {
              title: '收货人',
              prop: 'memberName',
            },
            {
              title: '收货人联系方式',
              prop: 'memberPhone',
            },
            {
              title: '收货地址',
              prop: 'memberAddress',
            },
            {
              title: '订单类型',
              prop: 'activityTypeCode',

            },
            {
              title: '订单金额（元）',
              prop: 'orderTotalPrice',
              valueType:'number'
            },
            {
              title: '实付金额（元）',
              prop: 'orderPayPrice',
              valueType:'number'
            },
            {
              title: '订单时间',
              prop: 'createTime',
            },
            {
              title: '订单状态',
              prop: 'orderState',
            },
          ]
        },

      ]
      let tb_arr = []
      res.data.forEach(item => {
        tb_arr.push({
          orderCode: item.orderCode || '/',
          buyMemberName: item.buyMemberName || '/',
          orderMemberPhone: item.orderMemberPhone || '/',
          payWay: item.payWay==="Alipay"?"支付宝":item.payWay==="WeChat"?"微信":item.payWay==="UnionPay"?"银联":item.payWay==="YsPay"?"银行卡":'/',
          memberName:item.memberName || '/',
          memberPhone:item.memberPhone || '/',
          memberAddress:item.memberAddress || '/',
          activityTypeCode:item.activityTypeCode == 0 ? '普通订单' : '砍价订单',
          orderTotalPrice: Number(item.orderTotalPrice/100).toFixed(2) || '/',
          orderPayPrice: Number(item.orderPayPrice/100).toFixed(2) || '/',
          createTime: item.createTime || '/',
          orderState: item.orderState ==='3'?"待付款":item.orderState==='4'?"待发货":item.orderState ==='5'?"待收货":item.orderState === "6"?"待分享":item.orderState==='9'?"交易成功":item.orderState ==='0'?"交易关闭":""
        })
      })
      exportSheetTable({ fileName: `商城订单${ orderState ==='3'?"待付款":orderState==='4'?"待发货":orderState ==='5'?"待收货":orderState === "6"?"待分享":orderState==='9'?"交易成功":orderState ==='0'?"交易关闭":""}`, tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false, })
    }
  }

  logDialogCancel = () => {
    this.setState({
      logisticsInformation: null,
      logVisible: false
    })
  }
  render() {
    const { columns, tabData, dataSource, loading, logVisible, logisticsInformation } = this.state
    return (
      <div className='p-layout-box'>
        <Logistics ref={this.logisticsRef}></Logistics>
        <StockOutModal
            // courierList={options}
            history={this.props.history}
            ref={this.stockOutModalRef}
            // footer={footer}
        />
        <SearchHeader getValue={this.getValue} exportDataList={(e)=>this.exportAll(e)} />
        <Tabs onChange={this.changeKey} >
          {
            tabData.map(v => {
              return <TabPane key={v.key} tab={v.tab}>
                <div className="p-layout-content-pagination">
                  <TheTable loading={loading} scroll={{ x: 'max-content', y: '63vh' }} columns={columns} dataSource={dataSource} />
                  <ThePagination
                    pageNo={this.state[`pageData${v.key}`].pageNo}
                    pageSize={this.state[`pageData${v.key}`].pageSize}
                    total={this.state[`total${v.key}`]}
                    pageChange={this.pageChange}
                  />
                </div>
              </TabPane>
            })
          }

        </Tabs>
        <TheDialog
          visible={logVisible}
          handleCancel={this.logDialogCancel}
          footer={null}
          title={'跟踪物流'}
        >
          <div style={{ height: 500, overflowY: 'auto' }}>
            {logisticsInformation &&
              <Steps progressDot current={logisticsInformation.length - 1} direction="vertical">
                {logisticsInformation.map(v => {
                  return <Step title={v.time} description={v.desc} />
                })}
              </Steps>}
            {!logisticsInformation && <span>暂无物流信息</span>}
          </div>
          <Space style={{ display: 'flex', justifyContent: 'center', marginTop: 20 }}>
            <Button type={'primary'} onClick={this.logDialogCancel}>确定</Button>
          </Space>
        </TheDialog>
      </div>
    )
  }
}
